<?php

namespace app\controller;

require '../extend/aws/aws-autoloader.php';

class Aws
{

    protected $_key;
    protected $secret;

    protected $_image_path = '/image'; //图片保存目录
    protected $_video_path = '/video'; //视频保存目录
    protected $_audio_path = '/audio'; //音频保存目录
    protected $_file_path = '/file'; //文件保存目录

    protected $_allow_ext = [
        0   => ['jpg', 'jpeg', 'gif', 'bmp', 'png'],    //图片格式
        1   => ['mp4', 'mov', 'mpeg', 'rmvb', 'avi'],   //视频
        2   => ['mp3', 'wav', 'wma', 'aac'],            //音频
        3   => ['pdf'],   //文件
    ];


    //链接亚马逊服务器
    public function __construct()
    {
//        $this->_key = 'OStpBCgFkiTIl8Nj9cEJNAxwHalgE2oRg2zm6AEln+ghwgn6zORMtmVOmDo=';
        $this->_key = 'AKIAQE43J644JSGMVYUX';
        $this->secret = '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';//secret
        $this->region = "ap-southeast-1";//区域
        $this->version = 'latest';//版本号
        $this->endpoint ='http://s3.ap-northeast-1.amazonaws.com';//公网访问地址
        $this->bucket = 'ysmhh';//桶
        try {
            $credentials = new \Aws\Credentials\Credentials($this->_key, $this->secret);
            $this->client = new \Aws\S3\S3Client([
                'version' => $this->version,
                'region' => $this->region,
                'credentials' => $credentials,
                'endpoint' => $this->endpoint,
                //设置访问权限  公开,不然访问不了
                'ACL'    => 'public-read',
//                'debug'   => true
            ]);
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            dump($msg);
            return false;
        }
        return true;
    }


    public function index(){

        $base64 = file_get_contents('123.png');

        $str = base64_encode($base64);
        dump($str);
        $res = $this->aws_uploadImage($str);
        dump($res);
    }

    /* OSS图片上传
    * @param type 1-base64图片
    * */
    public function aws_uploadImage($data,$type = 1,$program = 'all')
    {
        $save_path = str_replace('programname',$program,$this->_image_path);   //保存目录
        // if(request()->has('base64', 'post')){
        if($type = 1){
            // $data = $_POST['base64'];
            $result = $this->new_base64_upload($data);
            if ($result['code'] === 0){
                $fileResult = &$result['data'];
                $filePath = $fileResult['path'] . $fileResult['name'];
                $ossFileName = implode('/', [$save_path,date('Ymd'),$fileResult['name']]);
                // dump($filePath);
                // dump($ossFileName);
                // die;
                try {
                    $result = $this->client->putObject([
                        'Bucket'    => $this->bucket,
                        'Key'       => $ossFileName,
                        'Body'      => fopen($filePath,'rb'),
                        'ACL'       => 'public-read',
                    ]);
                    // dump($result);
                    $fileUrl = $result->get('ObjectURL');
                    // dump($fileUrl);
                    $arr = [
                        'oss_url' => $fileUrl,  //上传资源地址
                        'relative_path' => $ossFileName     //数据库保存名称(相对路径)
                    ];
                } catch(\Exception $e) {
                    return $e->getMessage();
                } finally {
                    unlink($filePath);
                }
                return array('code'=>0,'msg'=>'ok','url'=>$arr['oss_url']);
                // $this->jsonReturn(0, '成功oss', array('file' => $arr['oss_url']));
            }
            // $this->jsonReturn(1, $result['msg']);
            return array('code'=>1,'msg'=>$result['msg']);
        }else{
            /*获取到上传的文件*/
            //$file = request()->file('file');
            $file = $_FILES['file'];
            if ($file) {
                $name = $file['name'];
                // $format = strrchr($name, '.');//截取文件后缀名如 (.jpg)
                $ext = extend($name);	//获得图片文件名的后缀
                /*判断图片格式*/
                $allow_type = ['jpg', 'jpeg', 'gif', 'bmp', 'png'];
                if (! in_array($ext, $allow_type)) {
                    $this->jsonReturn(1, "文件格式不在允许范围内哦");

                }
                // 尝试执行
                try {
                    $result = $this->client->putObject([
                        'Bucket'    => $this->bucket,
                        'Key'       => $ossFileName,
                        'Body'      => fopen($filePath,'rb'),
                        'ACL'       => 'public-read',
                    ]);
                    // dump($result);
                    $fileUrl = $result->get('ObjectURL');
                    // dump($fileUrl);
                    $arr = [
                        'oss_url' => $fileUrl,  //上传资源地址
                        'relative_path' => $ossFileName     //数据库保存名称(相对路径)
                    ];
                } catch(\Exception $e) {
                    return $e->getMessage();
                }
                //将结果返回
                $this->jsonReturn(0, '成功上传到oss', array('file' => $arr['oss_url']));
            }
            $this->jsonReturn(1, "文件不存在");
        }
    }

    /**
     * 将Base64数据转换成二进制并存储到指定路径
     * @param        $base64
     * @param string $path
     * @return array
     */
    public function new_base64_upload($base64, $path = '') {
        $data = explode(',',$base64);
        trace($data,'api');
        unset($base64);
        if (count($data) !== 2){
            return['code'=>1,'msg'=>'文件格式错误'];
        }
        if (preg_match('/^(data:\s*image\/(\w+);base64)/', $data[0], $result)){
            $type = $result[2];
            if(!in_array($type,array('jpeg','jpg','gif','bmp','png'))){
                return['code'=>1,'msg'=>'文件格式不在允许范围内'];
            }
            $image_name = md5(uniqid()).'.'.$result[2];
            $image_path = app()->getRootPath() . 'public/Public/Uploads/news/';
            $image_file = $image_path . $image_name;
            //服务器文件存储路径
            try {
                if (file_put_contents($image_file, base64_decode($data[1]))) {
                    return['code'=>0, 'msg'=>'成功', 'data'=>['name' => $image_name, 'path' => $image_path]];
                } else {
                    return['code'=>1,'msg'=> '文件保存失败'];
                }
            }catch (\Exception $e){
                $msg = $e->getMessage();
                return['code'=>1,'msg'=>$msg];
            }
        }
        return ['code'=>1,'msg'=>'文件格式错误'];
    }

    /* AWS S3文件上传
    * @param type 类型 1-视频 2-音频 3-文件
    * */
    public function aws_uploadFile($type = 1,$program = 'all')
    {
        if($type == 1) {
            $save_path = str_replace('programname',$program,$this->_video_path);   //保存目录
        } elseif($type == 2) {
            $save_path = str_replace('programname',$program,$this->_audio_path);   //保存目录
        } elseif($type == 3) {
            $save_path = str_replace('programname',$program,$this->_file_path);   //保存目录
        } else{
            return ['code'=>1,'msg'=>'参数错误'];
        }

        /*获取到上传的文件*/
        // $file = request()->file('file');
        $file = $_FILES['file'];
        if ($file['error'] == 0) {
            $file = request()->file('file');
            $root_path = ROOT_PATH . 'public/Public/Uploads/news/';
            $info = $file->move($root_path);
            if ($info) {
                $file_name = $info->getFilename(); //随机生成的文件名
                $save_name = $info->getSaveName();
                // dump($root_path.$save_name);die;
            } else {
                //上传失败获取错误信息
                $this->error($file->getError());
            }
            // $name = $file['name'];
            // $format = strrchr($name, '.');//截取文件后缀名如 (.jpg)
            $ext = extend($file_name);	//获得图片文件名的后缀
            /*判断图片格式*/
            $allow_type = $this->_allow_ext[$type];
            if (!in_array($ext, $allow_type)) {
                return ['code'=>1,'msg'=>'文件格式错误'];
            }
            // 尝试执行
            try {
                //这里是有sha1加密 生成文件名 之后连接上后缀
                $fileName = $save_path .'/' . date("Ymd") . '/' . sha1(date('YmdHis', time()) . uniqid()) . '.' .$ext;

                // $config = config('aliyun_oss');
                // //实例化对象 将配置传入
                // $ossClient = new OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']);
                // //执行阿里云上传
                // $result = $ossClient->uploadFile($config['Bucket'], $fileName, $file['tmp_name']);
                // /*组合返回数据*/
                // $arr = [
                //     'oss_url' => $result['info']['url'],  //上传资源地址
                //     'relative_path' => $fileName     //数据库保存名称(相对路径)
                // ];
                $result = $this->client->putObject([
                    'Bucket'    => $this->bucket,
                    'Key'       => $fileName,
                    'Body'      => fopen($root_path.$save_name,'rb'),
                    'ACL'       => 'public-read',
                ]);
                // dump($result);
                $fileUrl = $result->get('ObjectURL');
                // dump($fileUrl);
                $arr = [
                    'oss_url' => $fileUrl,  //上传资源地址
                    'relative_path' => $fileName     //数据库保存名称(相对路径)
                ];
                unlink($root_path.$save_name);
            } catch (OssException $e) {
                return $e->getMessage();
            }
            //将结果返回
            return ['code'=>0,'msg'=>'ok','url'=>$arr['oss_url']];
        }
        return ['code'=>1,'msg'=>'请上传文件'];
    }

    public function getObject($key) {

        $result = $this->client->getObjectUrl($this->bucket,$key);
        // $result = $this->client->object($key)->get();
        // header("Content-Type: {$result['ContentType']}");
        // dump($result);die;
        return ['url'=>$result,'new_url'=>$result];

        $cmd = $this->client->getCommand('GetObject', [
            'Bucket' => $this->bucket,
            'Key' => $key,
        ]);

        $request = $this->client->createPresignedRequest($cmd, '+20 minutes');

        // Get the actual presigned-url
        $presignedUrl = (string)$request->getUri();
        return ['url'=>$presignedUrl,'new_url'=>$presignedUrl];
    }
    
    
}
